package com.yellowcong.realm;

import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.yellowcong.model.User;
import com.yellowcong.service.UserService;

/**
 * 创建日期:2017年9月23日 <br/>
 * 创建用户:yellowcong <br/>
 * 功能描述:用于授权操作
 */
public class SampleRealm extends AuthorizingRealm {
	
	@Autowired
    private UserService userService;

    /**
     * 用户授权 
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection paramPrincipalCollection) {
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        // 根据用户ID查询角色（role），放入到Authorization里。
        Set<String> roles = new HashSet<String>(); // 添加用户角色
        roles.add("administrator");
        info.setRoles(roles);
        // 根据用户ID查询权限（permission），放入到Authorization里。
        Set<String> permissions = new HashSet<String>(); // 添加权限
        permissions.add("/role/**");
        info.setStringPermissions(permissions);
        return info;
    }

    /**
     * 认证，用户登录
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken paramAuthenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) paramAuthenticationToken;

        User user = userService.login(token.getUsername());
        // token返回的是一个数组,将char类型转化为String类型
        String pswDate = new String(token.getPassword());
        // 当用户名 和密码都满足的情况，返回登陆信息
        if(pswDate.equals(user.getPassword())){
            return new SimpleAuthenticationInfo(token.getUsername(), token.getPassword(), getName());
        } else {
            // 当没有用户的时候，抛出异常
            throw new AuthenticationException();
        }
    }

}
